import React, { useEffect, useState, useRef } from 'react';
import { View, Text, TouchableOpacity, SafeAreaView, Image, ScrollView, Modal, TouchableWithoutFeedback } from 'react-native';
import { WebView } from 'react-native-webview';
import { DatePicker, Toast } from '@ant-design/react-native';
import { styles } from './styles';
import { searchOrderTreeApi, getCanAssignmentTaskApi, getTaskResourceOccupyInfoApi, assignmentTaskApi } from './api';

interface ProcessDispatchProps {
    onBackPress?: () => void;
}

const ProcessDispatch: React.FC<ProcessDispatchProps> = ({ onBackPress }) => {
    const webViewRef = useRef<WebView>(null);
    const [orderList, setOrderList] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);
    const [expandedOrders, setExpandedOrders] = useState<Set<string>>(new Set());
    const [selectedBatchOrders, setSelectedBatchOrders] = useState<Set<string>>(new Set());

    // 分页相关状态
    const [currentPage, setCurrentPage] = useState(1);
    const [totalPages, setTotalPages] = useState(1);
    const [totalRecords, setTotalRecords] = useState(0);
    const pageSize = 10;

    // 任务列表状态
    const [taskList, setTaskList] = useState<any[]>([]);

    // 任务选择状态
    const [selectedTask, setSelectedTask] = useState<string | null>(null);

    // Gantt数据状态
    const [ganttData, setGanttData] = useState<{
        data: any[];
        links: any[];
    } | null>(null);

    // 时间刻度状态
    const [selectedTimeScale, setSelectedTimeScale] = useState('day');

    // 资源详情弹窗状态
    const [isResourceDetailVisible, setIsResourceDetailVisible] = useState(false);
    const [selectedResource, setSelectedResource] = useState<any>(null);

    // 任务详情弹窗状态
    const [isTaskDetailVisible, setIsTaskDetailVisible] = useState(false);
    const [selectedTaskDetail, setSelectedTaskDetail] = useState<any>(null);

    // 派工相关状态
    const [workStartTime, setWorkStartTime] = useState<string | null>(null);
    const [workEndTime, setWorkEndTime] = useState<string | null>(null);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [startTimePickerVisible, setStartTimePickerVisible] = useState(false);
    const [endTimePickerVisible, setEndTimePickerVisible] = useState(false);

    // 切换时间刻度
    const changeTimeScale = (scale: string) => {
        setSelectedTimeScale(scale);
        const script = `
            if (window.handleReactNativeMessage) {
                window.handleReactNativeMessage({
                    type: 'changeTimeScale',
                    scale: '${scale}'
                });
            }
        `;
        webViewRef.current?.injectJavaScript(script);
    };

    // 调用搜索工单树接口
    const searchOrderTree = async (page: number = 1) => {
        try {
            setLoading(true);
            const response = await searchOrderTreeApi({
                current: page,
                size: pageSize
            });

            if (response && response.code === 200) {
                setOrderList(response.data?.records || []);
                setTotalPages(response.data?.pages || 1);
                setTotalRecords(response.data?.total || 0);
                setCurrentPage(page);
            } else {
                console.error('接口调用失败:', response?.msg || '未知错误');
            }
        } catch (error) {
            console.error('接口调用异常:', error);
        } finally {
            setLoading(false);
        }
    };

    // 上一页
    const goToPreviousPage = () => {
        if (currentPage > 1) {
            searchOrderTree(currentPage - 1);
        }
    };

    // 下一页
    const goToNextPage = () => {
        if (currentPage < totalPages) {
            searchOrderTree(currentPage + 1);
        }
    };

    // 切换工单展开/收起状态
    const toggleOrderExpansion = (workOrderNum: string) => {
        const newExpandedOrders = new Set(expandedOrders);
        if (newExpandedOrders.has(workOrderNum)) {
            newExpandedOrders.delete(workOrderNum);
        } else {
            newExpandedOrders.add(workOrderNum);
        }
        setExpandedOrders(newExpandedOrders);
    };

    // 选择/取消选择批次订单
    const toggleBatchOrderSelection = async (batchOrder: any) => {
        if (selectedBatchOrders.has(batchOrder.batch_order_num)) {
            // 如果已经选中，则取消选择
            setSelectedBatchOrders(new Set());
            setTaskList([]); // 清空任务列表
            setSelectedTask(null); // 清空选中的任务
            setGanttData(null); // 清空gantt数据
            console.log('取消选择批次订单:', batchOrder);
        } else {
            // 如果未选中，则选择当前订单（单选模式）
            setSelectedBatchOrders(new Set([batchOrder.batch_order_num]));
            setSelectedTask(null); // 清空之前选中的任务
            setGanttData(null); // 清空之前的gantt数据
            console.log('选择批次订单:', batchOrder);

            // 选择后调用获取可分配任务接口
            try {
                const response = await getCanAssignmentTaskApi(batchOrder.id);
                console.log('获取可分配任务成功:', response);

                if (response && response.code === 200 && response.data && response.data.task_list) {
                    setTaskList(response.data.task_list);
                } else {
                    setTaskList([]);
                }
            } catch (error) {
                console.error('获取可分配任务失败:', error);
                setTaskList([]);
            }
        }
    };

    // 选择/取消选择任务
    const toggleTaskSelection = async (task: any) => {
        if (selectedTask === task.id) {
            // 如果已经选中，则取消选择
            setSelectedTask(null);
            setGanttData(null); // 清空gantt数据
            console.log('取消选择任务:', task);
        } else {
            // 如果未选中，则选择当前任务（单选模式）
            setSelectedTask(task.id);
            console.log('选择任务:', task);

            // 选择任务后调用获取任务资源占用信息接口
            try {
                const response = await getTaskResourceOccupyInfoApi(task.id);
                console.log('获取任务资源占用信息成功:', response);

                if (response && response.code === 200 && response.data) {
                    // 处理数据结构，参考PC端逻辑
                    const data = response.data;
                    console.log('原始API数据:', data);

                    // 构建甘特图数据结构
                    const ganttElements: any[] = [];
                    const ganttLinks: any[] = [];

                    // 获取APS资源ID，参考PC端逻辑
                    const keys = ['', 'aps_station_id', 'aps_device_id', 'aps_station_id', 'aps_user_id', 'aps_line_id'];
                    const aps_resource_id = data[keys[task.capacity || 2]];
                    console.log('APS资源ID:', aps_resource_id, '任务产能类型:', task.capacity);

                    // 处理resource_list（左侧资源）
                    if (data.resource_list && Array.isArray(data.resource_list)) {
                        data.resource_list.forEach((resource: any) => {
                            // 设置资源基本信息，参考PC端逻辑
                            const resourceElement: any = {
                                id: resource.id,
                                text: resource.resource_name || resource.device_num || resource.station_num || resource.user_name || resource.line_num,
                                type: 'project',  // 明确标识为资源行
                                open: true,
                                parent: 0,
                                capacity: resource.capacity,
                                resource_id: resource.id,
                                // 关键：添加render属性，实现分割模式
                                render: 'split',
                                // 根据APS资源ID设置五角星：工序的work_device_id和资源的id相等显示五角星
                                is_aps: resource.id === aps_resource_id,
                                // 注意：资源行不包含task_flag属性
                                // 添加PC端一致的字段
                                key: resource.id
                            };

                            // 根据capacity设置不同的资源类型，参考PC端逻辑
                            // 注意：资源行（resource_list）所有产能类型都使用device_num作为资源名称
                            switch (resource.capacity) {
                                case 1:
                                case 3: {
                                    resourceElement.resource_num = resource.device_num;
                                    resourceElement.resource_name = resource.device_num;
                                    resourceElement.text = resource.device_num;
                                    resourceElement.resource_id = resource.id;
                                    break;
                                }
                                case 2: {
                                    resourceElement.resource_num = resource.device_num;
                                    resourceElement.resource_name = resource.device_num;
                                    resourceElement.text = resource.device_num;
                                    resourceElement.resource_id = resource.id;
                                    break;
                                }
                                case 4: {
                                    resourceElement.resource_num = resource.device_num;
                                    resourceElement.resource_name = resource.device_num;
                                    resourceElement.text = resource.device_num;
                                    resourceElement.resource_id = resource.id;
                                    break;
                                }
                                case 5: {
                                    resourceElement.resource_num = resource.device_num;
                                    resourceElement.resource_name = resource.device_num;
                                    resourceElement.text = resource.device_num;
                                    resourceElement.resource_id = resource.id;
                                    break;
                                }
                                default: {
                                    resourceElement.resource_num = resource.device_num;
                                    resourceElement.resource_name = resource.device_num;
                                    resourceElement.text = resource.device_num;
                                    resourceElement.resource_id = resource.id;
                                    break;
                                }
                            }

                            ganttElements.push(resourceElement);
                        });
                    }

                    // 处理resource_occupy_list（任务）
                    if (data.resource_occupy_list && Array.isArray(data.resource_occupy_list)) {
                        data.resource_occupy_list.forEach((taskItem: any) => {
                            // 找到对应的资源ID
                            const resourceId = taskItem.work_device_id || taskItem.work_station_id || taskItem.work_user_id || taskItem.work_line_id;

                            // 根据产能类型设置颜色，参考PC端逻辑
                            let taskColor = '#41bf42'; // 默认颜色
                            switch (taskItem.capacity) {
                                case 1:
                                case 3:
                                    taskColor = taskItem.station_color || '#41bf42';
                                    break;
                                case 2:
                                case 5:
                                    taskColor = taskItem.device_color || '#41bf42';
                                    break;
                                case 4:
                                    taskColor = taskItem.user_color || '#41bf42';
                                    break;
                                default:
                                    taskColor = taskItem.device_color || '#41bf42';
                                    break;
                            }

                            // 根据产能类型设置任务字段，参考PC端逻辑
                            let taskResourceNum, taskResourceName, taskLabel, taskResourceId;
                            switch (taskItem.capacity) {
                                case 1:
                                case 3: {
                                    taskResourceNum = taskItem.work_station_num;
                                    taskResourceName = taskItem.work_station_name;
                                    taskLabel = taskItem.work_station_name;
                                    taskResourceId = taskItem.work_station_id;
                                    break;
                                }
                                case 2: {
                                    taskResourceNum = taskItem.work_device_num;
                                    taskResourceName = taskItem.work_device_name;
                                    taskLabel = taskItem.work_device_name;
                                    taskResourceId = taskItem.work_device_id;
                                    break;
                                }
                                case 4: {
                                    taskResourceNum = taskItem.work_user_num;
                                    taskResourceName = taskItem.work_user_name;
                                    taskLabel = taskItem.work_user_name;
                                    taskResourceId = taskItem.work_user_id;
                                    break;
                                }
                                case 5: {
                                    taskResourceNum = taskItem.work_device_num;
                                    taskResourceName = taskItem.work_device_name;
                                    taskLabel = taskItem.work_device_name;
                                    taskResourceId = taskItem.work_device_id;
                                    break;
                                }
                                default: {
                                    taskResourceNum = taskItem.work_device_num;
                                    taskResourceName = taskItem.work_device_name;
                                    taskLabel = taskItem.work_device_name;
                                    taskResourceId = taskItem.work_device_id;
                                    break;
                                }
                            }

                            const taskElement: any = {
                                id: taskItem.id,
                                // 使用HTML格式，完全复制PC端实现，包含三角形图标
                                text: `<div style="position: relative;">
                                    ${taskItem.batch_order_num} #${taskItem.mbom_num}
                                    ${taskItem.task_flag ? `<div style="position:absolute;left: 50%;bottom:0px;transform:translateX(-50%);z-index:10;width:0;height:0;border-left:6px solid transparent;border-right:6px solid transparent;border-bottom:8px solid #ff4444;"></div>` : ''}
                                </div>`,
                                start_date: taskItem.work_start,
                                end_date: taskItem.work_end,
                                parent: resourceId, // 任务依附于对应的资源
                                type: 'task',
                                color: taskColor, // 使用根据产能类型设置的颜色
                                // 添加PC端一致的字段
                                resource_num: taskResourceNum,
                                resource_name: taskResourceName,
                                label: taskLabel,
                                resource_id: taskResourceId,
                                // 添加PC端一致的key字段
                                key: taskItem.id,
                                // 保存完整的任务信息用于详情显示
                                work_order_num: taskItem.work_order_num,
                                batch_order_num: taskItem.batch_order_num,
                                product_name: taskItem.product_name,
                                mbom_num: taskItem.mbom_num,
                                process_num: taskItem.process_num,
                                work_device_num: taskItem.work_device_num,
                                work_station_num: taskItem.work_station_num,
                                work_user_name: taskItem.work_user_name,
                                work_line_num: taskItem.work_line_num,
                                work_start: taskItem.work_start,
                                work_end: taskItem.work_end,
                                capacity: taskItem.capacity,
                                // 使用API返回的原始task_flag字段，参考PC端逻辑
                                task_flag: taskItem.task_flag || false,
                                show_star: taskItem.id === task.id
                            };



                            ganttElements.push(taskElement);
                        });
                    }

                    const ganttDataStructure = {
                        data: ganttElements,
                        links: ganttLinks
                    };

                    console.log('构建的甘特图数据:', ganttDataStructure);
                    setGanttData(ganttDataStructure);

                    // 向WebView发送数据
                    if (webViewRef.current) {
                        const script = `
                            if (window.handleReactNativeMessage) {
                                window.handleReactNativeMessage({
                                    type: 'updateGanttData',
                                    data: ${JSON.stringify(ganttDataStructure)}
                                });
                            }
                        `;
                        webViewRef.current.injectJavaScript(script);
                        console.log('甘特图数据已发送到WebView');
                    }
                } else {
                    setGanttData(null);
                    console.log('API返回数据格式不正确');
                }
            } catch (error) {
                console.error('获取任务资源占用信息失败:', error);
                setGanttData(null);
            }
        }
    };

    // 派工提交
    const handleDispatchSubmit = async () => {
        if (!selectedResource || !workStartTime || !workEndTime || !selectedTask) {
            Toast.info('请选择任务和派工时间', 2);
            return;
        }

        // 构建派工数据 - 参考PC端逻辑
        const dispatchData = {
            id: selectedTask, // 使用选中的任务ID，而不是资源ID
            capacity: selectedResource.capacity || 2,
            batch_order_num: selectedResource.batch_order_num || '',
            work_start: workStartTime,
            work_end: workEndTime,
            // 根据产能类型设置对应的资源ID
            work_device_id: selectedResource.capacity === 2 ? selectedResource.id : undefined,
            work_station_id: [1, 3].includes(selectedResource.capacity) ? selectedResource.id : undefined,
            work_user_id: selectedResource.capacity === 4 ? selectedResource.id : undefined,
            work_line_id: selectedResource.capacity === 5 ? selectedResource.id : undefined,
        };

        console.log('派工数据:', dispatchData);
        console.log('选中的资源:', selectedResource);

        // 设置提交状态
        setIsSubmitting(true);

        try {
            // 调用派工提交API
            const response = await assignmentTaskApi(dispatchData);

            console.log('派工提交API响应:', response);

            if (response.code === 200) {
                // 提交成功
                Toast.success(response.msg || '派工信息已提交', 2);
                // 关闭派工弹窗
                setIsResourceDetailVisible(false);
                // 重置状态
                setWorkStartTime(null);
                setWorkEndTime(null);
                setIsSubmitting(false);
            } else {
                // 提交失败
                Toast.fail(response.message || response.msg || '派工提交失败，请重试', 2);
            }
        } catch (error) {
            console.error('派工提交失败:', error);
            Toast.fail('网络请求失败，请检查网络连接后重试', 2);
        } finally {
            // 重置提交状态
            setIsSubmitting(false);
        }
    };

    // 清空派工信息
    const clearDispatchInfo = () => {
        setWorkStartTime(null);
        setWorkEndTime(null);
        setIsSubmitting(false);
        setStartTimePickerVisible(false);
        setEndTimePickerVisible(false);
    };

    // 格式化时间显示
    const formatTimeDisplay = (timeStr: string | null) => {
        if (!timeStr) return '';
        // 如果时间包含秒，则显示到秒；否则显示到分钟
        if (timeStr.includes(':00')) {
            return timeStr.slice(0, 16); // 显示到分钟
        }
        return timeStr; // 显示完整时间
    };

    // 组件挂载时调用接口
    useEffect(() => {
        searchOrderTree(1);
    }, []);

    // 渲染任务列表项
    const renderTaskItem = (task: any) => {
        // 产能类型映射
        const getCapacityTypeText = (capacity: number) => {
            switch (capacity) {
                case 1: return '工位产能';
                case 2: return '设备产能';
                case 3: return '无限产能';
                case 4: return '人产能';
                case 5: return '产线产能';
                default: return '未知产能';
            }
        };

        const isSelected = selectedTask === task.id;

        return (
            <TouchableOpacity
                key={task.id}
                style={[
                    styles.taskItem,
                    { borderLeftColor: task.process_color || '#007bff' },
                    isSelected && styles.taskItemSelected
                ]}
                onPress={() => toggleTaskSelection(task)}
            >
                {/* 选中状态的对号 */}
                {isSelected && (
                    <View style={styles.taskCheckmarkContainer}>
                        <Text style={styles.taskCheckmark}>✓</Text>
                    </View>
                )}

                <View style={styles.taskRow}>
                    <Text style={styles.taskLabel}>工序号:</Text>
                    <Text style={styles.taskValue}>{task.mbom_num}</Text>
                </View>
                <View style={styles.taskRow}>
                    <Text style={styles.taskLabel}>工艺号:</Text>
                    <Text style={styles.taskValue}>{task.process_num}</Text>
                </View>
                <View style={styles.taskRow}>
                    <Text style={styles.taskLabel}>工艺名称:</Text>
                    <Text style={styles.taskValue}>{task.process_name}</Text>
                </View>
                <View style={styles.taskRow}>
                    <Text style={styles.taskLabel}>产能类型:</Text>
                    <Text style={styles.taskValue}>{getCapacityTypeText(task.capacity)}</Text>
                </View>
                <View style={styles.taskRow}>
                    <Text style={styles.taskLabel}>推荐派工时间:</Text>
                    <Text style={styles.taskValue}>{task.aps_start} ~ {task.aps_end}</Text>
                </View>
                <View style={styles.taskRow}>
                    <Text style={styles.taskLabel}>实际派工时间:</Text>
                    <Text style={styles.taskValue}>{task.work_start} ~ {task.work_end}</Text>
                </View>
                <View style={styles.taskRow}>
                    <Text style={styles.taskLabel}>推荐设备:</Text>
                    <Text style={styles.taskValue}>{task.work_device_num}</Text>
                </View>
            </TouchableOpacity>
        );
    };

    // 渲染分页组件
    const renderPagination = () => {
        const canGoPrevious = currentPage > 1;
        const canGoNext = currentPage < totalPages;

        return (
            <View style={styles.paginationContainer}>
                <TouchableOpacity
                    style={[
                        styles.paginationArrow,
                        !canGoPrevious && styles.paginationArrowDisabled
                    ]}
                    onPress={goToPreviousPage}
                    disabled={!canGoPrevious}
                >
                    <Text style={[
                        styles.paginationArrowText,
                        !canGoPrevious && styles.paginationArrowTextDisabled
                    ]}>
                        &lt;
                    </Text>
                </TouchableOpacity>

                <View style={styles.paginationInfo}>
                    <Text style={styles.paginationText}>
                        {currentPage} / {totalPages}
                    </Text>
                </View>

                <TouchableOpacity
                    style={[
                        styles.paginationArrow,
                        !canGoNext && styles.paginationArrowDisabled
                    ]}
                    onPress={goToNextPage}
                    disabled={!canGoNext}
                >
                    <Text style={[
                        styles.paginationArrowText,
                        !canGoNext && styles.paginationArrowTextDisabled
                    ]}>
                        &gt;
                    </Text>
                </TouchableOpacity>
            </View>
        );
    };

    // 渲染工单列表项
    const renderOrderItem = (order: any) => {
        const isExpanded = expandedOrders.has(order.work_order_num);

        return (
            <View key={order.work_order_num} style={styles.orderItem}>
                <TouchableOpacity
                    style={styles.orderHeader}
                    onPress={() => toggleOrderExpansion(order.work_order_num)}
                >
                    <Text style={styles.orderNumber}>{order.work_order_num}</Text>
                    <Image
                        source={require('../../../../assets/xiala.png')}
                        style={[
                            styles.dropdownIcon,
                            isExpanded && styles.dropdownIconRotated
                        ]}
                        resizeMode="contain"
                    />
                </TouchableOpacity>

                {isExpanded && order.batch_order_list && (
                    <View style={styles.batchOrderList}>
                        {order.batch_order_list.map((batchOrder: any) => {
                            const isSelected = selectedBatchOrders.has(batchOrder.batch_order_num);
                            return (
                                <TouchableOpacity
                                    key={batchOrder.batch_order_num}
                                    style={[
                                        styles.batchOrderItem,
                                        isSelected && styles.batchOrderItemSelected
                                    ]}
                                    onPress={() => toggleBatchOrderSelection(batchOrder)}
                                >
                                    {/* 选中状态的对号 */}
                                    {isSelected && (
                                        <View style={styles.checkmarkContainer}>
                                            <Text style={styles.checkmark}>✓</Text>
                                        </View>
                                    )}

                                    <View style={styles.batchOrderRow}>
                                        <Text style={styles.batchOrderLabel}>单号:</Text>
                                        <Text style={styles.batchOrderValue}>{batchOrder.batch_order_num}</Text>
                                    </View>
                                    <View style={styles.batchOrderRow}>
                                        <Text style={styles.batchOrderLabel}>产品名称:</Text>
                                        <Text style={styles.batchOrderValue}>{batchOrder.product_name}</Text>
                                    </View>
                                    <View style={styles.batchOrderRow}>
                                        <Text style={styles.batchOrderLabel}>产品编码:</Text>
                                        <Text style={styles.batchOrderValue}>{batchOrder.product_encode}</Text>
                                    </View>
                                    <View style={styles.batchOrderRow}>
                                        <Text style={styles.batchOrderLabel}>产品规格:</Text>
                                        <Text style={styles.batchOrderValue}>{batchOrder.product_specs}</Text>
                                    </View>
                                    <View style={styles.batchOrderRow}>
                                        <Text style={styles.batchOrderLabel}>交期:</Text>
                                        <Text style={styles.batchOrderValue}>{batchOrder.delivery_date}</Text>
                                    </View>
                                    <View style={styles.batchOrderRow}>
                                        <Text style={styles.batchOrderLabel}>当前工序:</Text>
                                        <Text style={styles.batchOrderValue}>{batchOrder.current_mbom_num}</Text>
                                    </View>
                                </TouchableOpacity>
                            );
                        })}
                    </View>
                )}
            </View>
        );
    };

    return (
        <SafeAreaView style={styles.container}>
            <View style={styles.header}>
                {/* 背景图片 */}
                <Image
                    source={require('../../../../assets/terminal/home-header.png')}
                    style={styles.headerBackground}
                    resizeMode="cover"
                />

                {/* 头部内容 */}
                <View style={styles.headerContent}>
                    {/* Logo */}
                    {/* <Image
                        source={require('../../../../assets/terminal/home-logo.png')}
                        style={styles.logo}
                        resizeMode="contain"
                    /> */}

                    {/* 标题 */}
                    <Text style={styles.headerText}>
                        MES终端服务系统
                    </Text>
                </View>

                {/* 返回按钮 - 移到 headerContent 外面，与 PersonalCenter 页面结构一致 */}
                <TouchableOpacity
                    style={styles.backButton}
                    onPress={onBackPress}
                >
                    <Image
                        source={require('../../../../assets/fanhui.png')}
                        style={styles.backIcon}
                    />
                </TouchableOpacity>
            </View>

            {/* 页面内容 - 3栏布局 */}
            <View style={styles.content}>
                {/* 左侧栏 - 工单列表 */}
                <View style={styles.leftColumn}>
                    <View style={styles.leftColumnContent}>
                        <ScrollView
                            style={styles.orderListContainer}
                            showsVerticalScrollIndicator={false}
                            contentContainerStyle={styles.orderListContent}
                        >
                            {loading ? (
                                <View style={styles.loadingContainer}>
                                    <Text style={styles.loadingText}>加载中...</Text>
                                </View>
                            ) : orderList.length > 0 ? (
                                orderList.map(renderOrderItem)
                            ) : (
                                <View style={styles.emptyContainer}>
                                    <Text style={styles.emptyText}>暂无工单数据</Text>
                                </View>
                            )}
                        </ScrollView>
                        {renderPagination()}
                    </View>
                </View>

                {/* 中间栏 - 6分之一 */}
                <View style={styles.middleColumn}>
                    <View style={styles.columnContent}>
                        {taskList.length > 0 ? (
                            <ScrollView
                                style={styles.taskListContainer}
                                showsVerticalScrollIndicator={false}
                                contentContainerStyle={styles.taskListContent}
                            >
                                {taskList.map((task) => renderTaskItem(task))}
                            </ScrollView>
                        ) : (
                            <Text style={styles.columnText}>暂无任务</Text>
                        )}
                    </View>
                </View>

                {/* 右侧栏 - 3分之2 */}
                <View style={styles.rightColumn}>
                    <View style={styles.columnContent}>
                        {/* 时间刻度选择器 */}
                        <View style={styles.timeScaleContainer}>
                            <TouchableOpacity
                                style={[
                                    styles.timeScaleButton,
                                    selectedTimeScale === 'hour' && styles.activeTimeScaleButton
                                ]}
                                onPress={() => changeTimeScale('hour')}
                            >
                                <Text style={[
                                    styles.timeScaleButtonText,
                                    selectedTimeScale === 'hour' && styles.activeTimeScaleButtonText
                                ]}>小时</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={[
                                    styles.timeScaleButton,
                                    selectedTimeScale === 'day' && styles.activeTimeScaleButton
                                ]}
                                onPress={() => changeTimeScale('day')}
                            >
                                <Text style={[
                                    styles.timeScaleButtonText,
                                    selectedTimeScale === 'day' && styles.activeTimeScaleButtonText
                                ]}>天</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={[
                                    styles.timeScaleButton,
                                    selectedTimeScale === 'week' && styles.activeTimeScaleButton
                                ]}
                                onPress={() => changeTimeScale('week')}
                            >
                                <Text style={[
                                    styles.timeScaleButtonText,
                                    selectedTimeScale === 'week' && styles.activeTimeScaleButtonText
                                ]}>周</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={[
                                    styles.timeScaleButton,
                                    selectedTimeScale === 'month' && styles.activeTimeScaleButton
                                ]}
                                onPress={() => changeTimeScale('month')}
                            >
                                <Text style={[
                                    styles.timeScaleButtonText,
                                    selectedTimeScale === 'month' && styles.activeTimeScaleButtonText
                                ]}>月</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={[
                                    styles.timeScaleButton,
                                    selectedTimeScale === 'quarter' && styles.activeTimeScaleButton
                                ]}
                                onPress={() => changeTimeScale('quarter')}
                            >
                                <Text style={[
                                    styles.timeScaleButtonText,
                                    selectedTimeScale === 'quarter' && styles.activeTimeScaleButtonText
                                ]}>季度</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={[
                                    styles.timeScaleButton,
                                    selectedTimeScale === 'year' && styles.activeTimeScaleButton
                                ]}
                                onPress={() => changeTimeScale('year')}
                            >
                                <Text style={[
                                    styles.timeScaleButtonText,
                                    selectedTimeScale === 'year' && styles.activeTimeScaleButtonText
                                ]}>年</Text>
                            </TouchableOpacity>
                        </View>

                        {/* Gantt图表区域 */}
                        <View style={styles.ganttContainer}>
                            <WebView
                                ref={webViewRef}
                                javaScriptEnabled={true}
                                domStorageEnabled={true}
                                allowFileAccess={true}
                                mixedContentMode="compatibility"
                                onLoadEnd={() => webViewRef.current?.injectJavaScript('initGantt()')}
                                source={{
                                    html: `
                                        <!DOCTYPE html>
                                        <html>
                                        <head>
                                            <meta charset="utf-8">
                                            <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
                                            <title>工序派工甘特图</title>
                                            <style>
                                                html, body {
                                                    height: 100%;
                                                    padding: 0px;
                                                    margin: 0px;
                                                    overflow: hidden;
                                                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                                                }
                                                #gantt_here {
                                                    width: 100%;
                                                    height: 100%;
                                                }
                                                
                                                /* 甘特图任务样式优化 */
                                                .gantt_task_line {
                                                    border-radius: 3px;
                                                    font-weight: 500;
                                                    color: #333;
                                                }
                                                
                                                /* 资源组样式 */
                                                .gantt_row.gantt_project {
                                                    background-color: #f8f9fa;
                                                    font-weight: bold;
                                                }
                                                
                                                /* 五角星样式 */
                                                .star-icon {
                                                    position: absolute;
                                                    right: 5px;
                                                    top: 50%;
                                                    transform: translateY(-50%);
                                                    color: #ff4757;
                                                    font-size: 16px;
                                                    z-index: 10;
                                                }
                                                
                                                /* 资源五角星样式 */
                                                .gantt_row .gantt_cell[data-column-name="is_aps"] {
                                                    text-align: center;
                                                    font-size: 16px;
                                                    color: #ff4757;
                                                    font-weight: bold;
                                                }
                                            </style>
                                        </head>
                                        <body>
                                            <div id="gantt_here"></div>
                                            
                                            <script>
                                                // 创建日志函数
                                                function logToReactNative(message, level = 'log') {
                                                    // 确保console方法存在
                                                    if (console && console[level] && typeof console[level] === 'function') {
                                                        console[level](message);
                                                    } else {
                                                        // 如果方法不存在，使用console.log作为后备
                                                        console.log(message);
                                                    }
                                                    
                                                    if (window.ReactNativeWebView) {
                                                        window.ReactNativeWebView.postMessage(JSON.stringify({
                                                            type: 'log',
                                                            level: level,
                                                            message: message
                                                        }));
                                                    }
                                                }
                                                
                                                // 测试JavaScript执行
                                                logToReactNative('WebView JavaScript开始执行...');
                                                
                                                // 动态加载甘特图库
                                                function loadGanttLibrary() {
                                                    logToReactNative('开始加载甘特图JS库...');
                                                    var script = document.createElement('script');
                                                    script.src = 'file:///android_asset/components/gantt/codebase/dhtmlxgantt.js';
                                                    script.onload = function() {
                                                        logToReactNative('甘特图JS库加载成功');
                                                        loadGanttCSS();
                                                    };
                                                    script.onerror = function() {
                                                        logToReactNative('甘特图JS库加载失败', 'error');
                                                        showError('甘特图JS库加载失败');
                                                    };
                                                    document.head.appendChild(script);
                                                }
                                                
                                                // 加载甘特图CSS
                                                function loadGanttCSS() {
                                                    logToReactNative('开始加载甘特图CSS...');
                                                    var link = document.createElement('link');
                                                    link.rel = 'stylesheet';
                                                    link.href = 'file:///android_asset/components/gantt/codebase/dhtmlxgantt.css';
                                                    link.onload = function() {
                                                        logToReactNative('甘特图CSS加载成功');
                                                        initGanttChart();
                                                    };
                                                    link.onerror = function() {
                                                        logToReactNative('甘特图CSS加载失败', 'error');
                                                        showError('甘特图CSS加载失败');
                                                    };
                                                    document.head.appendChild(link);
                                                }
                                                
                                                // 初始化甘特图
                                                function initGanttChart() {
                                                    try {
                                                        // 配置甘特图
                                                        gantt.config.date_format = "%Y-%m-%d %H:%i:%s";
                                                        gantt.config.scale_height = 50;
                                                        gantt.config.row_height = 40;
                                                        gantt.config.min_column_width = 70;
                                                        
                                                        // 配置甘特图列 - 显示资源列和五角星列
                                                        gantt.config.columns = [
                                                            {name: "text", label: "资源", tree: true, align: "left", width: 100},
                                                            {
                                                                name: "is_aps", label: "", align: "center", width: 30,
                                                                template: function(item) {
                                                                    logToReactNative('渲染五角星列，item: ' + JSON.stringify(item));
                                                                    return item.is_aps ? '★' : '';
                                                                }
                                                            }
                                                        ];
                                                        
                                                        // 启用树形结构，但通过render: 'split'实现平铺显示
                                                        gantt.config.tree = true;
                                                        
                                                        logToReactNative('甘特图列配置已设置: ' + JSON.stringify(gantt.config.columns));
                                                        
                                                        // 确保甘特图能正确解析HTML
                                                        gantt.config.auto_scheduling = false;
                                                        gantt.config.work_time = true;
                                                        gantt.config.show_links = false;
                                                        gantt.config.drag_resize = false;
                                                        gantt.config.drag_move = false;
                                                        gantt.config.readonly = true;
                                                        
                                                        // 启用HTML支持，确保HTML文本能正确渲染
                                                        gantt.config.html_text = true;
                                                        
                                                        // 配置任务模板
                                                        gantt.templates.task_text = function(start, end, task) {
                                                            // 只有任务行才进入此模板
                                                            if (task.type !== 'task') {
                                                                return task.text || '';
                                                            }
                                                            
                                                            // HTML已经写在text字段中，直接返回
                                                            return task.text || '';
                                                        };
                                                        
                                                        // 配置任务颜色
                                                        gantt.templates.task_color = function(start, end, task) {
                                                            return task.color || "#41bf42";
                                                        };
                                                        
                                                        // 配置任务行样式
                                                        gantt.templates.task_class = function(start, end, task) {
                                                            var className = 'custom_task_color';
                                                            return className;
                                                        };
                                                        

                                                        
                                                        // 设置时间刻度 - 默认为天视图
                                                        gantt.config.scales = [
                                                            {unit: "month", step: 1, format: "%Y年%m月"},
                                                            {unit: "day", step: 1, format: "%j"}
                                                        ];
                                                        
                                                        // 初始化甘特图
                                                        logToReactNative('开始初始化甘特图到DOM元素...');
                                                        gantt.init("gantt_here");
                                                        logToReactNative('甘特图初始化完成');
                                                        
                                                        // 设置默认时间刻度为天视图
                                                        window.currentTimeScale = 'day';
                                                        
                                                        // 配置点击事件
                                                        gantt.attachEvent("onTaskClick", function(id, e) {
                                                            const task = gantt.getTask(id);
                                                            if (task && task.type === 'project') {
                                                                // 点击资源，发送资源详情消息
                                                                if (window.ReactNativeWebView) {
                                                                    window.ReactNativeWebView.postMessage(JSON.stringify({
                                                                        type: 'resourceClick',
                                                                        resource: {
                                                                            ...task,
                                                                            // 添加派工所需的字段
                                                                            capacity: task.capacity || 2,
                                                                            batch_order_num: task.batch_order_num || ''
                                                                        }
                                                                    }));
                                                                }
                                                            } else if (task && task.type === 'task') {
                                                                // 点击任务，发送任务详情消息
                                                                if (window.ReactNativeWebView) {
                                                                    window.ReactNativeWebView.postMessage(JSON.stringify({
                                                                        type: 'taskClick',
                                                                        task: task
                                                                    }));
                                                                }
                                                            }
                                                            return false;
                                                        });
                                                        
                                                        // 禁用默认编辑弹窗
                                                        gantt.attachEvent("onTaskDblClick", function() {
                                                            return false;
                                                        });
                                                        
                                                        // 禁用默认的右键菜单
                                                        gantt.attachEvent("onContextMenu", function() {
                                                            return false;
                                                        });
                                                        
                                                    } catch (error) {
                                                        logToReactNative('甘特图初始化失败: ' + error.message, 'error');
                                                        showError('甘特图初始化失败: ' + error.message);
                                                    }
                                                }
                                                
                                                // 显示错误信息
                                                function showError(message) {
                                                    logToReactNative('显示错误信息: ' + message, 'error');
                                                    var container = document.getElementById('gantt_here');
                                                    container.innerHTML = '<div style="padding: 20px; text-align: center; color: red;"><h3>错误</h3><p>' + message + '</p></div>';
                                                }
                                                
                                                // 页面加载完成后开始加载甘特图
                                                logToReactNative('页面加载完成，开始初始化甘特图...');
                                                
                                                if (typeof gantt !== 'undefined') {
                                                    logToReactNative('gantt对象已存在，直接初始化...');
                                                    initGanttChart();
                                                } else {
                                                    logToReactNative('gantt对象不存在，开始加载甘特图库...');
                                                    loadGanttLibrary();
                                                }
                                                
                                                // 监听来自React Native的消息
                                                logToReactNative('设置消息监听器...');
                                                
                                                // 创建全局函数供React Native调用
                                                window.handleReactNativeMessage = function(messageData) {
                                                    try {
                                                        logToReactNative('WebView收到React Native消息: ' + JSON.stringify(messageData));
                                                        
                                                        if (messageData.type === 'changeTimeScale') {
                                                            // 切换时间刻度
                                                            if (typeof gantt !== 'undefined') {
                                                                changeGanttTimeScale(messageData.scale);
                                                            }
                                                        } else if (messageData.type === 'updateGanttData') {
                                                            // 更新甘特图数据
                                                            logToReactNative('准备更新甘特图数据，数据类型: ' + typeof messageData.data);
                                                            logToReactNative('数据内容: ' + JSON.stringify(messageData.data));
                                                            
                                                            if (typeof gantt !== 'undefined') {
                                                                updateGanttData(messageData.data);
                                                                logToReactNative('甘特图数据已更新');
                                                            } else {
                                                                logToReactNative('gantt对象未定义，无法更新数据', 'error');
                                                            }
                                                        } else {
                                                            logToReactNative('未知消息类型: ' + messageData.type);
                                                        }
                                                    } catch (error) {
                                                        logToReactNative('处理消息失败: ' + error.message, 'error');
                                                        logToReactNative('错误详情: ' + error.stack, 'error');
                                                    }
                                                };
                                                
                                                logToReactNative('全局消息处理函数已设置: window.handleReactNativeMessage');
                                                
                                                // 切换甘特图时间刻度
                                                function changeGanttTimeScale(scale) {
                                                    // 保存当前选择的时间刻度到全局变量
                                                    window.currentTimeScale = scale;
                                                    
                                                    var scales = [];
                                                    
                                                    switch(scale) {
                                                        case 'hour':
                                                            scales = [
                                                                {unit: "day", step: 1, format: "%m月%d日"},
                                                                {unit: "hour", step: 1, format: "%H:00"}
                                                            ];
                                                            break;
                                                        case 'day':
                                                            scales = [
                                                                {unit: "month", step: 1, format: "%Y年%m月"},
                                                                {unit: "day", step: 1, format: "%j"}
                                                            ];
                                                            break;
                                                        case 'week':
                                                            scales = [
                                                                {unit: "month", step: 1, format: "%Y年%m月"},
                                                                {unit: "week", step: 1, format: "第%W周"}
                                                            ];
                                                            break;
                                                        case 'month':
                                                            scales = [
                                                                {unit: "year", step: 1, format: "%Y年"},
                                                                {unit: "month", step: 1, format: "%m月"}
                                                            ];
                                                            break;
                                                        case 'quarter':
                                                            scales = [
                                                                {unit: "year", step: 1, format: "%Y年"},
                                                                {unit: "quarter", step: 1, format: "Q%q"}
                                                            ];
                                                            break;
                                                        case 'year':
                                                            scales = [
                                                                {unit: "year", step: 1, format: "%Y年"}
                                                            ];
                                                            break;
                                                        default:
                                                            scales = [
                                                                {unit: "month", step: 1, format: "%Y年%m月"},
                                                                {unit: "day", step: 1, format: "%j"}
                                                            ];
                                                    }
                                                    
                                                    gantt.config.scales = scales;
                                                    gantt.render();
                                                    logToReactNative('时间刻度已切换到: ' + scale);
                                                }

                                                // 更新甘特图数据
                                                function updateGanttData(data) {
                                                    logToReactNative('=== 开始更新甘特图数据 ===');
                                                    try {
                                                        logToReactNative('接收到的数据格式:', JSON.stringify(data));
                                                        
                                                        // 清除现有数据
                                                        if (typeof gantt !== 'undefined') {
                                                            gantt.clearAll();
                                                            logToReactNative('甘特图数据已清除');
                                                        } else {
                                                            logToReactNative('gantt对象未定义，无法清除数据', 'error');
                                                            return;
                                                        }
                                                        
                                                        // 使用正确的数据格式
                                                        if (data.data && data.links) {
                                                            logToReactNative('使用标准数据格式更新甘特图');
                                                            gantt.parse({
                                                                data: data.data,
                                                                links: data.links
                                                            });
                                                        } else {
                                                            logToReactNative('使用兼容格式更新甘特图');
                                                            gantt.parse(data);
                                                        }
                                                        
                                                        // 重新渲染
                                                        gantt.render();
                                                        logToReactNative('甘特图数据更新完成');
                                                        
                                                        // 验证数据是否正确加载
                                                        var taskCount = gantt.getTaskByTime().length;
                                                        logToReactNative('甘特图当前任务数量: ' + taskCount);
                                                        
                                                    } catch (error) {
                                                        logToReactNative('更新甘特图数据失败: ' + error.message, 'error');
                                                        logToReactNative('错误详情: ' + error.stack, 'error');
                                                        showError('更新甘特图数据失败: ' + error.message);
                                                    }
                                                }
                                            </script>
                                        </body>
                                        </html>
                                    `}}
                                style={styles.webview}
                                startInLoadingState={true}
                                scalesPageToFit={true}
                                onMessage={(event) => {
                                    try {
                                        const data = JSON.parse(event.nativeEvent.data);
                                        console.log('收到WebView消息:', data);

                                        if (data.type === 'resourceClick') {
                                            console.log('点击资源:', data.resource);
                                            // 获取当前选中的批次订单，用于派工
                                            const currentBatchOrder = Array.from(selectedBatchOrders)[0];
                                            const resourceData = {
                                                ...data.resource,
                                                batch_order_num: currentBatchOrder || ''
                                            };
                                            console.log('派工资源数据:', resourceData);
                                            setSelectedResource(resourceData);

                                            // 设置默认派工时间为任务的推荐派工时间
                                            if (selectedTask && taskList.length > 0) {
                                                const currentTask = taskList.find(task => task.id === selectedTask);
                                                if (currentTask && currentTask.aps_start && currentTask.aps_end) {
                                                    setWorkStartTime(currentTask.aps_start);
                                                    setWorkEndTime(currentTask.aps_end);
                                                    console.log('设置默认派工时间:', currentTask.aps_start, '~', currentTask.aps_end);
                                                }
                                            }

                                            setIsResourceDetailVisible(true);
                                        } else if (data.type === 'taskClick') {
                                            console.log('点击任务:', data.task);
                                            setSelectedTaskDetail(data.task);
                                            setIsTaskDetailVisible(true);
                                        }
                                    } catch (error) {
                                        console.error('解析WebView消息失败:', error);
                                    }
                                }}
                                onError={(syntheticEvent) => {
                                    const { nativeEvent } = syntheticEvent;
                                    console.warn('WebView error: ', nativeEvent);
                                }}
                                onHttpError={(syntheticEvent) => {
                                    const { nativeEvent } = syntheticEvent;
                                    console.warn('WebView HTTP error: ', nativeEvent);
                                }}
                            />
                        </View>
                    </View>
                </View>
            </View>

            {/* 派工弹窗 */}
            <Modal
                visible={isResourceDetailVisible}
                transparent={true}
                animationType="slide"
                onRequestClose={() => {
                    clearDispatchInfo();
                    setIsResourceDetailVisible(false);
                }}
            >
                <View style={styles.modalOverlay}>
                    <View style={styles.modalContent}>
                        <View style={styles.modalHeader}>
                            <Text style={styles.modalTitle}>派工</Text>
                            <TouchableOpacity
                                onPress={() => {
                                    clearDispatchInfo();
                                    setIsResourceDetailVisible(false);
                                }}
                                style={styles.modalCloseButton}
                            >
                                <Text style={styles.modalCloseButtonText}>×</Text>
                            </TouchableOpacity>
                        </View>
                        <View style={styles.modalBody}>
                            {selectedResource && (
                                <View>
                                    <View style={styles.modalRow}>
                                        <Text style={styles.modalLabel}>任务ID：</Text>
                                        <Text style={styles.modalValue}>{selectedTask || 'N/A'}</Text>
                                    </View>

                                    <View style={styles.modalRow}>
                                        <Text style={styles.modalLabel}>资源名称：</Text>
                                        <Text style={styles.modalValue}>{selectedResource.text || 'N/A'}</Text>
                                    </View>

                                    <View style={styles.modalRow}>
                                        <Text style={styles.modalLabel}>批次号：</Text>
                                        <Text style={styles.modalValue}>{selectedResource.batch_order_num || 'N/A'}</Text>
                                    </View>

                                    {/* 推荐派工时间显示 */}
                                    {selectedTask && taskList.length > 0 && (() => {
                                        const currentTask = taskList.find(task => task.id === selectedTask);
                                        return currentTask && currentTask.aps_start && currentTask.aps_end ? (
                                            <View style={styles.modalRow}>
                                                <Text style={styles.modalLabel}>推荐时间：</Text>
                                                <Text style={styles.modalValue}>{currentTask.aps_start} ~ {currentTask.aps_end}</Text>
                                            </View>
                                        ) : null;
                                    })()}

                                    {/* 派工时间选择 */}
                                    <View style={styles.modalRow}>
                                        <Text style={styles.modalLabel}>派工时间：</Text>
                                    </View>
                                    <View style={styles.timeSelectionContainer}>
                                        <TouchableOpacity
                                            style={styles.timeSelector}
                                            onPress={() => {
                                                // 先隐藏派工弹窗
                                                setIsResourceDetailVisible(false);
                                                // 然后显示时间选择器
                                                setStartTimePickerVisible(true);
                                            }}
                                        >
                                            <Text style={[
                                                styles.timeText,
                                                !workStartTime && styles.placeholderText
                                            ]}>
                                                {workStartTime ? formatTimeDisplay(workStartTime) : '开始时间'}
                                            </Text>
                                        </TouchableOpacity>
                                        <Text style={styles.timeSeparator}>至</Text>
                                        <TouchableOpacity
                                            style={styles.timeSelector}
                                            onPress={() => {
                                                // 先隐藏派工弹窗
                                                setIsResourceDetailVisible(false);
                                                // 然后显示时间选择器
                                                setEndTimePickerVisible(true);
                                            }}
                                        >
                                            <Text style={[
                                                styles.timeText,
                                                !workEndTime && styles.placeholderText
                                            ]}>
                                                {workEndTime ? formatTimeDisplay(workEndTime) : '结束时间'}
                                            </Text>
                                        </TouchableOpacity>
                                    </View>
                                </View>
                            )}
                        </View>

                        {/* 底部按钮 */}
                        <View style={styles.modalFooter}>
                            <TouchableOpacity
                                style={[
                                    styles.submitButton,
                                    isSubmitting && styles.submitButtonDisabled
                                ]}
                                onPress={handleDispatchSubmit}
                                disabled={isSubmitting}
                            >
                                <Text style={[
                                    styles.submitButtonText,
                                    isSubmitting && styles.submitButtonTextDisabled
                                ]}>
                                    {isSubmitting ? '提交中...' : '确认'}
                                </Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={styles.cancelButton}
                                onPress={() => {
                                    clearDispatchInfo();
                                    setIsResourceDetailVisible(false);
                                }}
                                disabled={isSubmitting}
                            >
                                <Text style={styles.cancelButtonText}>取消</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </Modal>

            {/* DatePicker弹出层 */}
            <View style={styles.datePickerOverlay}>
                {/* 开始时间选择器 */}
                {startTimePickerVisible && (
                    <View style={styles.datePickerContainer}>
                        <DatePicker
                            visible={startTimePickerVisible}
                            value={workStartTime ? new Date(workStartTime) : (() => {
                                if (selectedTask && taskList.length > 0) {
                                    const currentTask = taskList.find(task => task.id === selectedTask);
                                    return currentTask?.aps_start ? new Date(currentTask.aps_start) : new Date();
                                }
                                return new Date();
                            })()}
                            precision="second"
                            minDate={new Date(2000, 0, 1)}
                            maxDate={new Date(2100, 11, 31, 23, 59, 59)}
                            onChange={date => {
                                if (date) {
                                    const y = date.getFullYear();
                                    const m = String(date.getMonth() + 1).padStart(2, '0');
                                    const d = String(date.getDate()).padStart(2, '0');
                                    const h = String(date.getHours()).padStart(2, '0');
                                    const min = String(date.getMinutes()).padStart(2, '0');
                                    const s = String(date.getSeconds()).padStart(2, '0');
                                    setWorkStartTime(`${y}-${m}-${d} ${h}:${min}:${s}`);
                                } else {
                                    // 如果没有选择时间，使用推荐时间
                                    if (selectedTask && taskList.length > 0) {
                                        const currentTask = taskList.find(task => task.id === selectedTask);
                                        if (currentTask?.aps_start) {
                                            setWorkStartTime(currentTask.aps_start);
                                        } else {
                                            setWorkStartTime('');
                                        }
                                    } else {
                                        setWorkStartTime('');
                                    }
                                }
                                setStartTimePickerVisible(false);
                                // 选择完时间后重新显示派工弹窗
                                setTimeout(() => {
                                    setIsResourceDetailVisible(true);
                                }, 100);
                            }}
                            format="YYYY-MM-DD HH:mm:ss"
                            onVisibleChange={(visible) => {
                                if (!visible) {
                                    setStartTimePickerVisible(false);
                                    // 时间选择器关闭后重新显示派工弹窗
                                    setTimeout(() => {
                                        setIsResourceDetailVisible(true);
                                    }, 100);
                                }
                            }}
                        />
                    </View>
                )}

                {/* 结束时间选择器 */}
                {endTimePickerVisible && (
                    <View style={styles.datePickerContainer}>
                        <DatePicker
                            visible={endTimePickerVisible}
                            value={workEndTime ? new Date(workEndTime) : (() => {
                                if (selectedTask && taskList.length > 0) {
                                    const currentTask = taskList.find(task => task.id === selectedTask);
                                    return currentTask?.aps_end ? new Date(currentTask.aps_end) : new Date();
                                }
                                return new Date();
                            })()}
                            precision="second"
                            minDate={new Date(2000, 0, 1)}
                            maxDate={new Date(2100, 11, 31, 23, 59, 59)}
                            onChange={date => {
                                if (date) {
                                    const y = date.getFullYear();
                                    const m = String(date.getMonth() + 1).padStart(2, '0');
                                    const d = String(date.getDate()).padStart(2, '0');
                                    const h = String(date.getHours()).padStart(2, '0');
                                    const min = String(date.getMinutes()).padStart(2, '0');
                                    const s = String(date.getSeconds()).padStart(2, '0');
                                    setWorkEndTime(`${y}-${m}-${d} ${h}:${min}:${s}`);
                                } else {
                                    // 如果没有选择时间，使用推荐时间
                                    if (selectedTask && taskList.length > 0) {
                                        const currentTask = taskList.find(task => task.id === selectedTask);
                                        if (currentTask?.aps_end) {
                                            setWorkEndTime(currentTask.aps_end);
                                        } else {
                                            setWorkEndTime('');
                                        }
                                    } else {
                                        setWorkEndTime('');
                                    }
                                }
                                setEndTimePickerVisible(false);
                                // 选择完时间后重新显示派工弹窗
                                setTimeout(() => {
                                    setIsResourceDetailVisible(true);
                                }, 100);
                            }}
                            format="YYYY-MM-DD HH:mm:ss"
                            onVisibleChange={(visible) => {
                                if (!visible) {
                                    setEndTimePickerVisible(false);
                                    // 时间选择器关闭后重新显示派工弹窗
                                    setTimeout(() => {
                                        setIsResourceDetailVisible(true);
                                    }, 100);
                                }
                            }}
                        />
                    </View>
                )}
            </View>

            {/* 任务详情弹窗 */}
            <Modal
                visible={isTaskDetailVisible}
                transparent={true}
                animationType="fade"
                onRequestClose={() => setIsTaskDetailVisible(false)}
            >
                <TouchableWithoutFeedback onPress={() => setIsTaskDetailVisible(false)}>
                    <View style={styles.modalOverlay}>
                        <TouchableWithoutFeedback onPress={(e) => e.stopPropagation()}>
                            <View style={styles.modalContent}>
                                <View style={styles.modalHeader}>
                                    <Text style={styles.modalTitle}>任务详情</Text>
                                    <TouchableOpacity
                                        onPress={() => setIsTaskDetailVisible(false)}
                                        style={styles.modalCloseButton}
                                    >
                                        <Text style={styles.modalCloseButtonText}>×</Text>
                                    </TouchableOpacity>
                                </View>
                                <View style={styles.modalBody}>
                                    {selectedTaskDetail && (
                                        <View>
                                            <View style={styles.modalRow}>
                                                <Text style={styles.modalLabel}>工单号：</Text>
                                                <Text style={styles.modalValue}>{selectedTaskDetail.work_order_num || 'N/A'}</Text>
                                            </View>
                                            <View style={styles.modalRow}>
                                                <Text style={styles.modalLabel}>批次：</Text>
                                                <Text style={styles.modalValue}>{selectedTaskDetail.batch_order_num || 'N/A'}</Text>
                                            </View>
                                            <View style={styles.modalRow}>
                                                <Text style={styles.modalLabel}>产品名称：</Text>
                                                <Text style={styles.modalValue}>{selectedTaskDetail.product_name || 'N/A'}</Text>
                                            </View>
                                            <View style={styles.modalRow}>
                                                <Text style={styles.modalLabel}>工序号：</Text>
                                                <Text style={styles.modalValue}>{selectedTaskDetail.mbom_num || 'N/A'}</Text>
                                            </View>
                                            <View style={styles.modalRow}>
                                                <Text style={styles.modalLabel}>工艺号：</Text>
                                                <Text style={styles.modalValue}>{selectedTaskDetail.process_num || 'N/A'}</Text>
                                            </View>
                                            <View style={styles.modalRow}>
                                                <Text style={styles.modalLabel}>派工设备：</Text>
                                                <Text style={styles.modalValue}>{selectedTaskDetail.work_device_num || 'N/A'}</Text>
                                            </View>
                                            <View style={styles.modalRow}>
                                                <Text style={styles.modalLabel}>开始时间：</Text>
                                                <Text style={styles.modalValue}>{selectedTaskDetail.work_start || 'N/A'}</Text>
                                            </View>
                                            <View style={styles.modalRow}>
                                                <Text style={styles.modalLabel}>结束时间：</Text>
                                                <Text style={styles.modalValue}>{selectedTaskDetail.work_end || 'N/A'}</Text>
                                            </View>
                                        </View>
                                    )}
                                </View>
                            </View>
                        </TouchableWithoutFeedback>
                    </View>
                </TouchableWithoutFeedback>
            </Modal>
        </SafeAreaView>
    );
};

export default ProcessDispatch;